package gui;

import gui.SimpleTable.MyTableCellRenderer;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.*; 
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

import controllers.OBLSettings;

import Entity.Book;
import Entity.BorrowRecored;

import messagesPacks.ViewHistoryMessage;

import java.awt.Color;
import java.awt.SystemColor;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
/**
 * This class representing a Subscriber View history Gui
 * Date: 25/12/2012
 * @author Roman
 *
 */
public class SubscriberViewHistoryUI extends JPanel
{		
		private static final long serialVersionUID = 1L;
		private static WelcomeUI wui;
		JButton btnLogout;
		JButton btnExit;
		private JLabel lblOblSubscriber;
		private JSeparator separator;
		private JButton btnBack;
		private SimpleTable historyTable ; 
		
		//private LibrarianUI subUI = null;
		//private SubscriberUI subUI = null;
		SubscriberUI subUI = null;
		private JList detailsList;
		
		private DefaultListModel<String> lstActivityLogOBJ;
		private JList lstActivityLog;
		private JScrollPane scrollPane;
		
		ViewHistoryMessage answer;

	public SubscriberViewHistoryUI(SubscriberUI fatherPanel)
	{
		super();
		initialize();
	    this.subUI = fatherPanel;
		
	}

	/**
	 * This method initializes the panel
	 */
	private void initialize()
	{
		setLayout(null);
		this.setSize(OBLSettings.pane2Size[0],OBLSettings.pane2Size[1]);
		separator = new JSeparator();
		separator.setBounds(-17, 57, 855, 20);
		add(separator);
		
		lblOblSubscriber = new JLabel("OBL  Subscriber history");
		lblOblSubscriber.setFont(new Font("Tahoma", Font.BOLD, 20));
		lblOblSubscriber.setBounds(270, 11, 260, 35);
		add(lblOblSubscriber);
		
		btnLogout = new JButton("Logout");
		btnLogout.setFont(new Font("Tahoma", Font.BOLD, 15));
		btnLogout.setBounds(614, 11, 83, 41);
		add(btnLogout);
		
		btnExit = new JButton("Exit");
		btnExit.setFont(new Font("Tahoma", Font.BOLD, 15));
		btnExit.setBounds(707, 11, 83, 41);
		add(btnExit);
		
		btnBack = new JButton("Back");
		btnBack.setFont(new Font("Tahoma", Font.BOLD, 15));
		btnBack.setBounds(26, 11, 83, 41);
		add(btnBack);
		
		String ColNames[] = { "Borrow Number","Book ISBN","CopyID", "Book Name","Borrow Date","Return Date","Actual Return Date"};
		historyTable = new SimpleTable(null, ColNames, 8, 60, 780, 360);
		historyTable.setColCenter(historyTable.table.getColumnCount());
	    add(historyTable.tblScrollPane,BorderLayout.CENTER);
	    
	    lstActivityLogOBJ = new DefaultListModel<String>();
		detailsList = new JList(lstActivityLogOBJ);
		detailsList.setOpaque(false);
		detailsList.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 15));
		detailsList.setBackground(SystemColor.control);
		detailsList.setBorder(new LineBorder(SystemColor.controlShadow));
		detailsList.setBounds(8, 430, 780, 130);
		add(detailsList);

		
	
//================================================================		
//                         Action Listeners
//================================================================			
		
		btnBack.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				historyTable.model.setRowCount(0);
				lstActivityLogOBJ.removeAllElements();
				

				  WelcomeUI.wui.switchPanel("OBL System - Subscriber",subUI ,OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);

			}
		});
//=============================================================================================		

		historyTable.table.getSelectionModel().addListSelectionListener(new ListSelectionListener() 
		{
			public void valueChanged(ListSelectionEvent e) 
			{
				JTable table = historyTable.table;

				if(table.getRowCount() > 0)	
				{	
					int row = table.getSelectedRow();

					if(row>=0)
					{ 
						lstActivityLogOBJ.removeAllElements();
						
			    		Object[] rowData = new Object[table.getColumnCount()];  
			    		for (int i = 0; i < table.getColumnCount(); i++) 
			    		{  
					         rowData[i] = table.getValueAt(row, i);  
			    		} 
			    		
		
			    		for(BorrowRecored var : answer.getBorrowList())
			    		{	 
			    			if(var.borrowNumber ==  Integer.parseInt( rowData[0].toString()))
			    			  {
			    				lstActivityLogOBJ.addElement("lateness days : " +calculateLatnessPiriod(var.returnDate ,var.actualReturnDate));
			    				lstActivityLogOBJ.addElement("book returned : " +var.bookReturned);
			    				lstActivityLogOBJ.addElement("book lost : " +var.bookLost);
			    				lstActivityLogOBJ.addElement("fines: " +String.valueOf(calculateFine(var.bookLost ,
			    						calculateLatnessPiriod(var.returnDate ,var.actualReturnDate)))+"\u20AA".toCharArray()[0]);
			    						
			    			  }

			    		 }//for
			    		
					}//if
				}//if
			}
			
		});
	    MyTableCellRenderer myTCR = new MyTableCellRenderer(historyTable);
	    for (int i=0; i < historyTable.table.getColumnCount(); i++)
	    	historyTable.table.getColumnModel().getColumn(i).setCellRenderer(myTCR);
	}//init
//=============================================================================================		
	public int calculateLatnessPiriod(String returnDate , String actualReturnDate) 
	{
		int lateDays = 0 ;

		if(!returnDate.isEmpty()&&!actualReturnDate.isEmpty())
		{	
			try 
			{
				Date ret_date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(returnDate);
				Date acu_ret_date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(actualReturnDate);
				
				if(ret_date.getYear() == acu_ret_date.getYear())	
				{	
					if(ret_date.getMonth() == acu_ret_date.getMonth()) //6.12  = 6.12
					{
						int days = acu_ret_date.getDay() - ret_date.getDay();
						
						if(days >= 0)
							lateDays = days;
					}
					else if(ret_date.getMonth() < acu_ret_date.getMonth()) //10.2.12 < 3.6.12
					{
						int months = (acu_ret_date.getMonth() - ret_date.getMonth()) * 30;
						lateDays = months ;
						int days = acu_ret_date.getDay() - ret_date.getDay();
						if(days >= 0)
						  lateDays = months + days ;
					}
					
				}
				else if(ret_date.getYear() < acu_ret_date.getYear())
				{
					if(ret_date.getMonth() == acu_ret_date.getMonth()) //6.12  =  6.12
					{
						int days = acu_ret_date.getDay() - ret_date.getDay();
						int years = (acu_ret_date.getYear() - ret_date.getYear()) * 365;//years in days
						lateDays = years;
						if(days >= 0)
							lateDays += days;
					}
					else if(ret_date.getMonth() < acu_ret_date.getMonth()) //10.2.12 < 3.6.12
					{
						int years = (acu_ret_date.getYear() - ret_date.getYear()) * 365;//years in days
						int months = (acu_ret_date.getMonth() - ret_date.getMonth()) * 30;//months in days
						lateDays += months + years ; 
						int days = acu_ret_date.getDay() - ret_date.getDay();
						if(days >= 0)
						   lateDays +=  days ;
					}

				 }

			}//try
			catch (ParseException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

	     }
		return lateDays;
	}
//=============================================================================================	
	public int calculateFine(String bookLost ,int LateDays )
	{
		int fine = 0 ;
		
		if(bookLost.equals("yes"))
		{
			fine = OBLSettings.FineForLoosingBook;
		}
		
		fine = fine + ( LateDays*OBLSettings.FineForLatnnessDay);
		
		return fine ; 
	}
//=============================================================================================	
	public void showHistory(String userID) //calling this function from subscriberUI -> btnViewHistory.addActionListener(new ActionListener() {...
	{
		answer = subUI.subscriberUIP.viewSubscriberHistory(userID);
		
		int last_row_index;
		historyTable.model.setRowCount(0);
		
		if(answer.getMsg_result() == 0)
			JOptionPane.showMessageDialog( WelcomeUI.wui, "there was an error in retrieving your history " ,"Warning",JOptionPane.WARNING_MESSAGE);
		else if(answer.getBorrowList().isEmpty())
			JOptionPane.showMessageDialog( WelcomeUI.wui, "you don't have any history " ,"Information",JOptionPane.INFORMATION_MESSAGE);
		else
		{	
			
			for(BorrowRecored var : answer.getBorrowList())
			{
				historyTable.model.addRow(new Object[] {var.borrowNumber,var.bookISBN,var.copyID,var.bookName,var.borrowDate,var.returnDate,var.actualReturnDate});
				last_row_index = historyTable.model.getRowCount() - 1;
				System.out.println("inserted tow index = "+last_row_index);
				if (var.bookReturned.equals("yes"))
					historyTable.setRowColour(last_row_index,Color.green);
				else
					historyTable.setRowColour(last_row_index,Color.orange);
				if (var.bookLost.equals("yes"))
					historyTable.setRowColour(last_row_index,Color.red);
			}
			
		 }
	}
	public void paintComponent(Graphics g) 
	{
		g.drawImage((OBLSettings.IMG_DEFAULT_BACKGROUND).getImage(), 0, 0, OBLSettings.pane2Size[0], OBLSettings.pane2Size[1],null);
		
	}
	
}//class